package com.xinfu.newproject.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xinfu.newproject.R;
import com.xinfu.newproject.adapter.community.ChooseCommunityAdapter;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.bean.community.ExistCommunityBean;
import com.xinfu.newproject.bean.community.GetCommunityBean;
import com.xinfu.newproject.bean.community.GetCommunityBody;
import com.xinfu.newproject.bean.community.InsertCommunityBean;
import com.xinfu.newproject.bean.login.LoginBean;
import com.xinfu.newproject.callback.MyCallBack;
import com.xinfu.newproject.custom_view.CommonPopupWindow;
import com.xinfu.newproject.model.IModel;
import com.xinfu.newproject.presenter.ExistCommunityPresenter;
import com.xinfu.newproject.presenter.GetCommunityPresenter;
import com.xinfu.newproject.presenter.InsertCommunityPresenter;
import com.xinfu.newproject.util.BToast;
import com.xinfu.newproject.util.SPUtils;
import com.xinfu.newproject.view.IView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

import static com.xinfu.newproject.contants.Constant.COMMUNITY;
import static com.xinfu.newproject.contants.Constant.COMMUNITYID;
import static com.xinfu.newproject.contants.Constant.LOGIN;
import static com.xinfu.newproject.contants.Constant.TENANTID;

public class ChooseCommunityActivity extends BaseActivity implements IModel.IGetCommunityModel, IView.IGetCommunityView, BaseQuickAdapter.OnItemClickListener, IView.IInsertCommunityView, IView.IExistCommunityView, TextWatcher {

    @BindView(R.id.head_back)
    ImageView backIv;

    @BindView(R.id.activity_choose_community_rv)
    RecyclerView mRecyclerView;

    @BindView(R.id.activity_choose_community_current_rv)
    RecyclerView currentRv;

    @BindView(R.id.head_text)
    TextView titleTv;

    @BindView(R.id.activity_choose_community_all_tv)
    TextView allTv;

    @BindView(R.id.activity_choose_community_search_et)
    EditText searchEt;

    private List<String> products;
    private ArrayAdapter communityCityAdapter;
    private PopupWindow popupWindow;

    private ChooseCommunityAdapter chooseCommunityAdapter;
//    private ChooseCommunityTwoAdapter chooseCommunityAdapter2;

    private GetCommunityPresenter getCommunityPresenter = new GetCommunityPresenter(this);
    private InsertCommunityPresenter insertCommunityPresenter = new InsertCommunityPresenter(this);
    private ExistCommunityPresenter existCommunityPresenter = new ExistCommunityPresenter(this);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_community);
        ButterKnife.bind(this);
        registerBack();
        initViewBind();
        initLisener();

    }

    private void initLisener() {
        getCommunityPresenter.getCommunity();
        existCommunityPresenter.existCommunity();
        searchEt.addTextChangedListener(this);

    }

    private void initViewBind() {
        titleTv.setText("选择小区");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        currentRv.setLayoutManager(new LinearLayoutManager(this));
        chooseCommunityAdapter = new ChooseCommunityAdapter();
//        chooseCommunityAdapter2 = new ChooseCommunityTwoAdapter();
        mRecyclerView.setAdapter(chooseCommunityAdapter);
//        currentRv.setAdapter(chooseCommunityAdapter2);
        chooseCommunityAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (getIntent().getIntExtra("type", 0) == 0) {
                    tenantId = dataList.get(position).getTenantId();
                    projectId = dataList.get(position).getId();
                    projectName = dataList.get(position).getName();
                    address = dataList.get(position).getAddress();
                    insertCommunityPresenter.getCommunity();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("community", new Gson().toJson(dataList.get(position)));
                    bundle.putString("name", dataList.get(position).getName());
                    bundle.putString("communityId", dataList.get(position).getId());
                    bundle.putString("tenantId", dataList.get(position).getTenantId());
                    bundle.putString("address", dataList.get(position).getAddress());
                    Intent intent = new Intent();
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
//        chooseCommunityAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                if (getIntent().getIntExtra("type", 0) == 0) {
//                    insertCommunityPresenter.getCommunity(position);
//                } else {
//                    Intent intent = new Intent();
//                    intent.putExtra("community", new Gson().toJson(dataList.get(position)));
//                    intent.putExtra("name", dataList.get(position).getName());
//                    setResult(RESULT_OK, intent);
//                    finish();
//                }
//            }
//        });
    }

    @OnClick({R.id.activity_choose_community_all_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.activity_choose_community_all_tv:
                initSelectPopup();
                break;

        }
    }

    /**
     * 初始化popup窗口
     */
    private void initSelectPopup() {
        products = new ArrayList<>();
        products.add("全部");
        products.add("上海");
        products.add("苏州");
        // 设置适配器
        //向下弹出pop
        //设置空白的背景色
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.alpha = 0.3f;
//        getWindow().setAttributes(lp);
        if (popupWindow != null && popupWindow.isShowing()) {
            return;
        }
        popupWindow = new CommonPopupWindow.Builder(this)
                .setView(R.layout.popwindow_activity_community)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
//                .setAnimationStyle(R.style.AnimDown)
                .setViewOnclickListener(new CommonPopupWindow.ViewInterface() {
                    @Override
                    public void getChildView(View view, int layoutResId) {
                        ListView rv = view.findViewById(R.id.popwindow_activity_community_rv);
                        communityCityAdapter = new ArrayAdapter(ChooseCommunityActivity.this, R.layout.popwindow_item_choose_city, products);
                        rv.setAdapter(communityCityAdapter);
                        rv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                allTv.setText(products.get(i));
                                popupWindow.dismiss();
                            }
                        });
                    }
                })
                .setOutsideTouchable(true)
                .create();

        popupWindow.showAsDropDown(allTv);
    }


    @Override
    public void getCommunity(GetCommunityBody getCommunityBody, MyCallBack<GetCommunityBean> callBack) {

    }

    @Override
    public String header() {
        String response = (String) SPUtils.get(this, LOGIN, "0");
        LoginBean.ResultBean resultBean = new Gson().fromJson(response, LoginBean.ResultBean.class);
        Log.i("testChooseCommunity", resultBean.getToken());
        return resultBean.getToken();
    }

    @Override
    public String userId() {
        String response = (String) SPUtils.get(this, LOGIN, "0");
        LoginBean.ResultBean resultBean = new Gson().fromJson(response, LoginBean.ResultBean.class);

        return resultBean.getUserInfo().getId();
    }

    String projectId, tenantId, projectName, address;

    @Override
    public String auditRes() {
        return "1";
    }

    @Override
    public String projectId() {
        return projectId;
    }

    @Override
    public String tenantId() {
        return tenantId;
    }

    @Override
    public void showToast(String content) {
        BToast.showText(this, content);
    }

    @Override
    public void closeDispose(Disposable disposable) {

    }

    @Override
    public void insertCommunity(InsertCommunityBean community) {
        Intent intent = new Intent();
        if (getIntent().getIntExtra("type", 0) == 0) {
            SPUtils.put(ChooseCommunityActivity.this, COMMUNITY, projectName);
            SPUtils.put(ChooseCommunityActivity.this, COMMUNITYID, projectId);
            SPUtils.put(ChooseCommunityActivity.this, TENANTID, tenantId);
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("address", address);
            bundle.putString("communityId", projectId);
            bundle.putString("tenantId", tenantId);
            intent.putExtras(bundle);
        }
        intent.putExtra("name", projectName);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void showProgress() {
        showLoding();
    }

    @Override
    public void hideProgress() {
        hideLoding();
    }

    @Override
    public void getData(ExistCommunityBean existCommunityBean) {
//        if (chooseCommunityAdapter2 != null) {
//            dataList2 = existCommunityBean.getResult();
//            chooseCommunityAdapter2.setNewData(existCommunityBean.getResult());
//        }
    }

    List<GetCommunityBean.ResultBean> dataList;
    List<ExistCommunityBean.ResultBean> dataList2;

    @Override
    public void getData(GetCommunityBean getCommunityBean) {

        if (chooseCommunityAdapter != null) {
            dataList = getCommunityBean.getResult();
            chooseCommunityAdapter.setNewData(getCommunityBean.getResult());
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (searchEt.getText().length() != 0) {
            if (dataList != null) {
                List<GetCommunityBean.ResultBean> searchList = new ArrayList<>();
                for (int i = 0; i < dataList.size(); i++) {
                    if (dataList.get(i).getName().contains(searchEt.getText().toString())) {
                        searchList.add(dataList.get(i));
                    }
                }
                chooseCommunityAdapter.setNewData(searchList);
            }
        } else {
            chooseCommunityAdapter.setNewData(dataList);
        }
    }
}
